package de.in.michael.unnamed;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.List;

public class InputHandler implements KeyListener
{
	public class Key
	{
		private int presses, absorbs;
		public boolean down, clicked;

		public Key()
		{
			keys.add(this);
		}

		public void tick()
		{
			if (absorbs < presses)
			{
				absorbs++;
				clicked = true;
			}
			else
			{
				clicked = false;
			}
		}

		public void toggle(boolean pressed)
		{
			if (down != pressed)
			{
				down = pressed;
			}

			if (pressed)
			{
				presses++;
			}
		}
	}

	public List<Key> keys = new ArrayList<Key>();

	public Key up = new Key();
	public Key down = new Key();
	public Key left = new Key();
	public Key right = new Key();
	public Key enter = new Key();
	public Key escape = new Key();

	public InputHandler(GameComponent gameComponent)
	{
		gameComponent.addKeyListener(this);
	}

	public void tick()
	{
		for (int i = 0; i < keys.size(); i++)
		{
			keys.get(i).tick();
		}
	}

	public void keyPressed(KeyEvent ke)
	{
		toggle(ke, true);
	}

	public void keyReleased(KeyEvent ke)
	{
		toggle(ke, false);
	}

	public void toggle(KeyEvent ke, boolean pressed)
	{
		if (ke.getKeyCode() == KeyEvent.VK_UP)
		{
			up.toggle(pressed);
		}

		if (ke.getKeyCode() == KeyEvent.VK_DOWN)
		{
			down.toggle(pressed);
		}

		if (ke.getKeyCode() == KeyEvent.VK_LEFT)
		{
			left.toggle(pressed);
		}

		if (ke.getKeyCode() == KeyEvent.VK_RIGHT)
		{
			right.toggle(pressed);
		}

		if (ke.getKeyCode() == KeyEvent.VK_ENTER)
		{
			enter.toggle(pressed);
		}

		if (ke.getKeyCode() == KeyEvent.VK_ESCAPE)
		{
			escape.toggle(pressed);
		}
	}

	public void releaseAll()
	{
		for (int i = 0; i < keys.size(); i++)
		{
			keys.get(i).down = false;
		}
	}

	public void keyTyped(KeyEvent ke)
	{
	}
}
